﻿using Microsoft.AspNetCore.SignalR;

using SignalRServerDemo.Hubs;

namespace SignalRServerDemo
{
    public class LongTimePushWorkService : BackgroundService
    {
        private readonly IHubContext<LongTimePushHub> _longTimePushHub;

        public LongTimePushWorkService(IHubContext<LongTimePushHub> longTimePushHub)
        {
            _longTimePushHub = longTimePushHub;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            const string groupId = "longtimepush-group-2022";
            while (stoppingToken.IsCancellationRequested == false)
            {
                try
                {
                    var pushData = new TransPushData(Guid.NewGuid().ToString(), $"当前系统时间戳：{Environment.TickCount64}", DateTime.Now);
                    await _longTimePushHub.Clients.Group(groupId).SendAsync("ClientHook", pushData);

                    await Task.Delay(1000, stoppingToken);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }
    }
}
